package com.autolinq.servlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import net.sf.json.JSONObject;

import com.autolinq.util.http.HttpUtil;



/**
 * 
 * @author 简爱微萌
 * @Email zyw205@gmail.com
 * 接口权限中设置OAuth2.0网页授权 域名 如：www.wechat68.com
 * 授权访问的URL：https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx614c453e0d1dcd12&redirect_uri=http://www.wechat68.com/Javen/OauthTest&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect
 */
public class Oauth2Servlet extends HttpServlet {
	protected final Logger logger = Logger.getLogger(this.getClass().getName());
	private String get_access_token_url="https://api.weixin.qq.com/sns/oauth2/access_token?" +
        "appid=APPID" +
        "&secret=SECRET&" +
        "code=CODE&grant_type=authorization_code";
	private String get_userinfo="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	
	public Properties prop = new Properties();// 属性集合对象
    private String classpath = this.getClass().getResource("/").getPath();
    private static final long serialVersionUID = -644518508267758016L;
    
    public synchronized void init() throws ServletException{
    	logger.debug("init");                
		try {
			FileInputStream fis = new FileInputStream(classpath
					+ "/prop.properties");// 属性文件输入流
			prop.load(fis);// 将属性文件流装载到Properties对象中
			fis.close();// 关闭流
		} catch (Exception ex) {
			ex.printStackTrace();
		}
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8"); 
        String code=request.getParameter("code");
        
        System.out.println("code="+code);
        
        get_access_token_url=get_access_token_url.replace("APPID", prop.getProperty("wechatAppID"));
        get_access_token_url=get_access_token_url.replace("SECRET", prop.getProperty("wechatSECRET"));
        get_access_token_url=get_access_token_url.replace("CODE", code);
        
        get_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?"+"appid="+prop.getProperty("wechatAppID")+"&secret="+prop.getProperty("wechatSECRET")+"&" +
                "code="+code+"&grant_type=authorization_code";
        
        System.out.println("get_access_token_url="+get_access_token_url);
        String json=HttpUtil.getUrl(get_access_token_url);
        System.out.println("json="+json);
        
        JSONObject jsonObject=JSONObject.fromObject(json);
        String access_token=jsonObject.getString("access_token");
        String openid=jsonObject.getString("openid");
        
        System.out.println("access_token="+access_token);
        
        
        String fromUser = request.getParameter("openid");
        String type = request.getParameter("type");
        String tripid = request.getParameter("tripid");
        
        System.out.println("fromUser="+fromUser);
        System.out.println("toUser="+openid);
        System.out.println("type="+type);
        if("1".equals(type)){
        	response.sendRedirect("join.html?inviteUser="+fromUser+"&acceptUser="+openid);
        }else if("2".equals(type)){
        	response.sendRedirect("invite_trip.html?inviteUser="+fromUser+"&acceptUser="+openid+"&id="+tripid);
        }
        
        
//        get_userinfo=get_userinfo.replace("ACCESS_TOKEN", access_token);
//        get_userinfo=get_userinfo.replace("OPENID", openid);
//        
//        get_userinfo="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
//        System.out.println("get_userinfo="+get_userinfo);
//        
//        String userInfoJson=HttpUtil.getUrl(get_userinfo);
//        
//        JSONObject userInfoJO=JSONObject.fromObject(userInfoJson);
//        
//        String user_openid=userInfoJO.getString("openid");
//        String user_nickname=userInfoJO.getString("nickname");
//        String user_sex=userInfoJO.getString("sex");
//        String user_province=userInfoJO.getString("province");
//        String user_city=userInfoJO.getString("city");
//        String user_country=userInfoJO.getString("country");
//        String user_headimgurl=userInfoJO.getString("headimgurl");
//
//    //    response.sendRedirect("redit.html");
//        response.setContentType("text/html; charset=utf-8");
//        PrintWriter out = response.getWriter();
//        out.println("");
//        out.println("");
//        out.println("  ");
//        out.println("  ");
//        out.print("    This is ");
//        out.print(this.getClass());
//        out.println(", using the POST method \n");
//        out.println("openid:"+user_openid+"\n\n");        
//        out.println("nickname:"+user_nickname+"\n\n");        
//        out.println("sex:"+user_sex+"\n\n");        
//        out.println("province:"+user_province+"\n\n");        
//        out.println("city:"+user_city+"\n\n");        
//        out.println("country:"+user_country+"\n\n");
//        out.println("<img src='"+user_headimgurl+"'/>");
//        out.println(">");
//        out.println("  ");
//        out.println("");
//        out.flush();
//        out.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("");
        out.println("");
        out.println("  ");
        out.println("  ");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  ");
        out.println("");
        out.flush();
        out.close();
    }


}